package com.vdg.lockapp;

import group.pals.android.lib.ui.lockpattern.LockPatternActivity;

import java.util.ArrayList;

import android.annotation.TargetApi;
import android.app.ActivityManager;
import android.app.ActivityManager.RunningServiceInfo;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.ServiceConnection;
import android.os.Build;
import android.os.Bundle;
import android.os.IBinder;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentActivity;
import android.support.v4.app.FragmentPagerAdapter;
import android.support.v4.view.ViewPager;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TabHost;
import android.widget.TabHost.TabSpec;
import android.widget.TabWidget;
import android.widget.TextView;

import com.google.ads.AdRequest;
import com.google.ads.AdSize;
import com.google.ads.AdView;
import com.vdg.lockapp.service.LockService;
import com.vdg.lockapp.service.LockService.LocalBinder;
import com.vdg.ui.view.AppRater;
import com.vdg.util.Utilities;

public class MainActivity extends FragmentActivity {
	private static final int PICKER_ACTION = 111;
	TabHost mTabHost;
	ViewPager mViewPager;
	TabsAdapter mTabsAdapter;
	private static final String TAG = "MainActivity";
	private LinearLayout mLnAds;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.fragment_tabs_pager);
		// Button btn1 = (Button) findViewById(R.id.button1);
		// btn1.setOnClickListener(new OnClickListener() {
		//
		// @Override
		// public void onClick(View v) {
		// // TODO Auto-generated method stub
		// Intent intent = new Intent(MainActivity.this,
		// ListAppPickerActivity.class);
		// startActivity(intent);
		// }
		// });
		mTabHost = (TabHost) findViewById(android.R.id.tabhost);
		mTabHost.setup();

		mViewPager = (ViewPager) findViewById(R.id.pager);

		mTabsAdapter = new TabsAdapter(this, mTabHost, mViewPager);
		mTabsAdapter
				.addTab(mTabHost
						.newTabSpec(getResources().getString(R.string.list_app))
						.setIndicator(
								prepareTabView(
										this,
										getResources().getString(
												R.string.app_lock),
										R.drawable.tab_portfolio, R.color.white)),
						FragmentListApplications.class, null);
		mTabsAdapter.addTab(
				mTabHost.newTabSpec(getResources().getString(R.string.setting))
						.setIndicator(
								prepareTabView(
										this,
										getResources().getString(
												R.string.setting),
										R.drawable.tab_menu, R.color.white)),
				SettingFragment.class, null);
		// mTabsAdapter.addTab(
		// mTabHost.newTabSpec("About US").setIndicator("About US"),
		// FragmentStackSupport.class, null);
		mLnAds = (LinearLayout) findViewById(R.id.ln_ads);
		AdSize testSize = AdSize.createAdSize(AdSize.SMART_BANNER, this);
		mLnAds.getLayoutParams().height = testSize.getHeightInPixels(this);
		AdView ad = (AdView) findViewById(R.id.adView);
		ad.loadAd(new AdRequest());
		if (savedInstanceState != null) {
			mTabHost.setCurrentTabByTag(savedInstanceState.getString("tab"));
		}
		AppRater.app_launched(this);
	}

	private static View prepareTabView(Context context, String title,
			int drawable, int color) {
		View view = LayoutInflater.from(context).inflate(
				R.layout.tab_indicator, null);
		TextView txvTitle = (TextView) view.findViewById(R.id.title);
		ImageView imvIcon = (ImageView) view.findViewById(R.id.icon);
		imvIcon.setImageResource(drawable);
		// txvTitle.setTextColor(ColorStateList.valueOf(context.getResources().getColor(R.color.text_color)));
		txvTitle.setText(title);
		// try {
		// XmlResourceParser parser = context.getResources().getXml(
		// R.color.text_color);
		// ColorStateList colors = ColorStateList.createFromXml(
		// context.getResources(), parser);
		// txvTitle.setTextColor(colors);
		// } catch (Exception e) {
		// e.printStackTrace();
		// }
		// txvTitle.setTextColor(new ColorStateList(new int[][] {
		// new int[] { android.R.attr.state_enabled }, new int[] {} },
		// new int[] { context.getResources().getColor(R.color.white),
		// context.getResources().getColor(R.color.white) }));
		return view;
	}

	@Override
	protected void onSaveInstanceState(Bundle outState) {
		super.onSaveInstanceState(outState);
		outState.putString("tab", mTabHost.getCurrentTabTag());
	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		// Inflate the menu; this adds items to the action bar if it is present.
		getMenuInflater().inflate(R.menu.activity_main, menu);
		return true;
	}

	@Override
	protected void onDestroy() {
		// TODO Auto-generated method stub
		super.onDestroy();
	}

	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		switch (requestCode) {
		case SettingFragment.REQ_CREATE_PATTERN: {
			if (resultCode == RESULT_OK) {
				char[] pattern = data
						.getCharArrayExtra(LockPatternActivity.EXTRA_PATTERN);
				Log.v(TAG, " data return= " + String.valueOf(pattern));
				Utilities.savePatternToSharedPreferences(MainActivity.this,
						pattern);
			}
			break;
		}
		}
	}

	public static class TabsAdapter extends FragmentPagerAdapter implements
			TabHost.OnTabChangeListener, ViewPager.OnPageChangeListener {
		private final Context mContext;
		private final TabHost mTabHost;
		private final ViewPager mViewPager;
		private ArrayList<TabSpec> mListTabSpec;
		private final ArrayList<TabInfo> mTabs = new ArrayList<TabInfo>();

		static final class TabInfo {
			private final String tag;
			private final Class<?> clss;
			private final Bundle args;

			TabInfo(String _tag, Class<?> _class, Bundle _args) {
				tag = _tag;
				clss = _class;
				args = _args;
			}
		}

		static class DummyTabFactory implements TabHost.TabContentFactory {
			private final Context mContext;

			public DummyTabFactory(Context context) {
				mContext = context;
			}

			@Override
			public View createTabContent(String tag) {
				View v = new View(mContext);
				v.setMinimumWidth(0);
				v.setMinimumHeight(0);
				return v;
			}
		}

		public TabsAdapter(FragmentActivity activity, TabHost tabHost,
				ViewPager pager) {
			super(activity.getSupportFragmentManager());
			mContext = activity;
			mTabHost = tabHost;
			mViewPager = pager;
			mTabHost.setOnTabChangedListener(this);
			mViewPager.setAdapter(this);
			mViewPager.setOnPageChangeListener(this);
			mListTabSpec = new ArrayList<TabHost.TabSpec>();
		}

		public void addTab(TabHost.TabSpec tabSpec, Class<?> clss, Bundle args) {
			tabSpec.setContent(new DummyTabFactory(mContext));
			String tag = tabSpec.getTag();
			mListTabSpec.add(tabSpec);
			TabInfo info = new TabInfo(tag, clss, args);
			mTabs.add(info);
			mTabHost.addTab(tabSpec);
			notifyDataSetChanged();
		}

		@Override
		public int getCount() {
			return mTabs.size();
		}

		@Override
		public Fragment getItem(int position) {
			TabInfo info = mTabs.get(position);
			return Fragment.instantiate(mContext, info.clss.getName(),
					info.args);
		}

		@Override
		public void onTabChanged(String tabId) {
			int position = mTabHost.getCurrentTab();
			mViewPager.setCurrentItem(position);
			Log.v("debug", "" + position + "       " + mListTabSpec.size());
			// if (mListTabSpec.size() > 1) {
			// if (position == 0) {
			// mListTabSpec.get(0).setIndicator(
			// prepareTabView(mContext, mContext.getResources()
			// .getString(R.string.app_lock),
			// R.drawable.tab_portfolio, R.color.black));
			// mListTabSpec.get(1).setIndicator(
			// prepareTabView(mContext, mContext.getResources()
			// .getString(R.string.setting),
			// R.drawable.tab_menu, R.color.black));
			// } else {
			// mListTabSpec.get(0).setIndicator(
			// prepareTabView(mContext, mContext.getResources()
			// .getString(R.string.app_lock),
			// R.drawable.tab_portfolio, R.color.black));
			// mListTabSpec.get(1).setIndicator(
			// prepareTabView(mContext, mContext.getResources()
			// .getString(R.string.setting),
			// R.drawable.tab_menu, R.color.black));
			// }
			// }
		}

		@Override
		public void onPageScrolled(int position, float positionOffset,
				int positionOffsetPixels) {
		}

		@Override
		public void onPageSelected(int position) {
			// Unfortunately when TabHost changes the current tab, it kindly
			// also takes care of putting focus on it when not in touch mode.
			// The jerk.
			// This hack tries to prevent this from pulling focus out of our
			// ViewPager.
			TabWidget widget = mTabHost.getTabWidget();
			int oldFocusability = widget.getDescendantFocusability();
			widget.setDescendantFocusability(ViewGroup.FOCUS_BLOCK_DESCENDANTS);
			mTabHost.setCurrentTab(position);
			widget.setDescendantFocusability(oldFocusability);
		}

		@Override
		public void onPageScrollStateChanged(int state) {
		}
	}
}
